Factory
Defines an interface for creating an object but lets subclasses alter the type of object that will be created. This pattern is useful when the creation process varies based on input conditions.
Structure
Product (interface): Defines the interface for objects created by the factory method.Concrete Product: Implements the product interface.Factory: Declares the factory method, which returns an object of type Product. It may also define the default implementation of the factory method.
Example
// Product interface
interface Animal {
void speak();
}
// Concrete Products
class Dog implements Animal {
public void speak() {
System.out.println("Bark!");
}
}
class Cat implements Animal {
public void speak() {
System.out.println("Meow!");
}
}
// Factory
class AnimalFactory {
public Animal getAnimal(String type) {
if ("Dog".equalsIgnoreCase(type)) {
return new Dog();
} else if ("Cat".equalsIgnoreCase(type)) {
return new Cat();
}
return null;
}
}